import { Component, OnInit, ViewChild, Input, Output, EventEmitter, ElementRef } from '@angular/core';

@Component({
  selector: 'app-tags-add',
  templateUrl: './tags-add.component.html',
  styleUrls: ['./tags-add.component.scss']
})
export class TagsAddComponent implements OnInit {
  @ViewChild('inputElement', { static: false }) inputElement?: ElementRef;

  @Input() tagLists: string[] = [];
  @Output() tagListsChange = new EventEmitter();

  // tags = [];
  inputVisible = false;
  inputValue = '';

  constructor() { }

  ngOnInit(): void {
  }

  handleClose(removedTag: {}): void {
    this.tagLists = this.tagLists.filter(tag => tag !== removedTag);
    this.tagListsChange.emit(this.tagLists);
  }

  sliceTagName(tag: string): string {
    const isLongTag = tag.length > 20;
    return isLongTag ? `${tag.slice(0, 20)}...` : tag;
  }

  showInput(): void {
    this.inputVisible = true;
    setTimeout(() => {
      this.inputElement?.nativeElement.focus();
    }, 10);
  }

  handleInputConfirm(): void {
    if (this.inputValue && this.tagLists.indexOf(this.inputValue) === -1) {
      this.tagLists = [...this.tagLists, this.inputValue];
    }
    this.inputValue = '';
    this.inputVisible = false;

    this.tagListsChange.emit(this.tagLists);
  }
}
